<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:pu:pmPuAppvouch:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmPuAppvouchsList>
        <BasicTable
          @register="registerPmPuAppvouchsTable"
          @row-click="handlePmPuAppvouchsRowClick"
        />
        <a-button
          class="mt-2"
          @click="handlePmPuAppvouchsAdd"
          v-auth="'material:pu:pmPuAppvouch:edit'"
          v-if="!status"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>

        <a-button
          v-if="!status"
          class="mt-2 ml-2"
          @click="openModal(true, {})"
          v-auth="'material:pu:pmPuAppvouch:edit'"
        >
          <Icon icon="simple-line-icons:calendar" /> {{ t('批量修改需求日期') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmPuAppAppVouch"
        completeText="提交"
        :loading="loadingRef"
        :auth="'material:pu:pmPuAppvouch:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="materialList"
      v-show="false"
      selectType="materialpuSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
    <Modal @register="register" @modifyxqDate="modifyxqDate" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialPuPmPuAppvouchForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmPuAppvouch,
    pmPuAppvouchSave,
    pmPuAppvouchForm,
  } from '/@/api/material/pu/pmPuAppvouch';
  import { BpmButton } from '/@/components/Bpm';
  import { ListSelect } from '/@/components/ListSelect';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { u8InvClsTreeData, u8ItemClsTreeData } from '/@/api/zfgsCommon/zfgsCommon';
  import { useModal } from '/@/components/Modal';
  import Modal from './Modal.vue';
  

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.pu.pmPuAppvouch');
  const { showMessage } = useMessage();
  const record = ref<PmPuAppvouch>({} as PmPuAppvouch);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('发起材料请购单') : t('编辑材料请购单'),
  }));

  const loadingRef = ref(false);
  let listSelectRef = ref([]);
  let queryParams = ref({});
  let materialList = ref<any>('');

  let status = ref(false);
    

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('请购信息'),
      field: 'puInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('请购单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        disabled: true,
        maxlength: 100,
      },
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        readonly: true,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        allowClear: false,
        canSelectParent: false,
        onChange: async (e) => {
          queryParams.value = {
            pcode: e,
          };
          let arr = await pmPuAppvouchsTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            await pmPuAppvouchsTable.deleteTableDataRecord(item);
          });
        },
        disabled:computed(() => status.value) ,
      },
      required: true,
    },
   
    // {
    //   label: t('采购类型'),
    //   field: 'potype',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'u8_po_type',
    //     allowClear: true,
    //     disabled:computed(() => status.value) ,
    //   },
    //   required: true,
    // },
    {
      label: t('存货分类'),
      field: 'invCls',
      fieldLabel: 'invClsName',
      component: 'TreeSelect',
      componentProps: {
        api: u8InvClsTreeData,
        // params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        allowClear: true,
        disabled:computed(() => status.value) ,
      },
      required: true,
    },

    {
      label: t('请购备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        // rows: 5,
        disabled:computed(() => status.value) ,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('创建时间'),
      field: 'createDate',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
      required: true,
      ifShow: () => !record.value.isNewRecord,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('创建人名称'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
      required: true,
      ifShow: () => !record.value.isNewRecord,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('材料信息'),
      field: 'materialInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'pmPuAppvouchsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmPuAppvouchsList',
    },
  ];

  const [register, { openModal }] = useModal();

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmPuAppvouchsTable, pmPuAppvouchsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmPuAppvouchsDelete.bind(this, record),
          },
          auth: 'material:pu:pmPuAppvouch:edit',
          ifShow: () => !status.value,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmPuAppvouchsTableData(_res: Recordable) {
    pmPuAppvouchsTable.setColumns([
      {
        title: t('材料编码'),
        dataIndex: 'mcode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('材料名称'),
        dataIndex: 'pmMaterial.mname',
        width: 150,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('规格型号'),
        dataIndex: 'pmMaterial.mstd',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('单位'),
        dataIndex: 'pmMaterial.unit',
        width: 60,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      // {
      //   title: t('项目大类'),
      //   dataIndex: 'itemCls',
      //   dataLabel: 'itemClsName',
      //   width: 130,
      //   align: 'left',
      //   editRow: !status.value,
      //   editComponent: 'TreeSelect',
      //   editComponentProps: {
      //     api: u8ItemClsTreeData, 
      //     // params: { isLoadUser: true, userIdPrefix: '' },
      //     canSelectParent: false,
      //     allowClear: true,
      //   },
      //   editRule: true,
      // },
      {
        title: t('需求日期'),
        dataIndex: 'xqDate',
        width: 200,
        align: 'center',
        editRow: !status.value,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 120,
        align: 'center',
        // editRow: true,
        editRow: !status.value,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        editRow: !status.value,
        editComponent: 'Input',
        editRule: false,
      },
    ]);
    pmPuAppvouchsTable.setTableData(record.value.pmPuAppvouchsList || []);
  }

  function handlePmPuAppvouchsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmPuAppvouchsAdd() {
    /*pmPuAppvouchsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });*/
    if (!getFieldsValue().projectno) {
      showMessage('请先选择项目名称！');
      return;
    }
    listSelectRef.value = [];
    let arr = pmPuAppvouchsTable.getDataSource().map((item) => {
      return item.mcode;
    });
    queryParams.value.selIds = arr.join(',')
    materialList.value.handleInputClick();
  }

  function handlePmPuAppvouchsDelete(record: Recordable) {
    pmPuAppvouchsTable.deleteTableDataRecord(record);
  }

  async function modifyxqDate(data) {
    for (const record of pmPuAppvouchsTable.getDataSource()) {
      record.xqDate = data.xqDate;
      console.log(record,'record');
      console.log(data,'data');
    }
  }

  async function getPmPuAppvouchsList() {
    let pmPuAppvouchsListValid = true;
    let pmPuAppvouchsList: Recordable[] = [];
    for (const record of pmPuAppvouchsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmPuAppvouchsListValid = false;
      }
      pmPuAppvouchsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmPuAppvouchsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmPuAppvouchsList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmPuAppvouchsListValid) {
      throw { errorFields: [{ name: ['pmPuAppvouchsList'] }] };
    }
    return pmPuAppvouchsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmPuAppvouchForm(data);
    record.value = (res.pmPuAppvouch || {}) as PmPuAppvouch;
    record.value.__t = new Date().getTime();
    queryParams.value = {
      pcode: record.value.projectno,
    };
    status.value = record.value.status == '9' || record.value.status == '6' || !record.value.status?false:true
    setFieldsValue(record.value);
    setPmPuAppvouchsTableData(res);
    setDrawerProps({ loading: false });
  });

  // 材料选择
  async function handSelect(selectData) {
    let arr = await pmPuAppvouchsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.mcode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmPuAppvouchsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          projectno: item.pcode,
          pmMaterial: {
            mcode: item.mcode,
            mname: item.mname,
            projectno: item.pcode,
            unit: item.unit,
            mstd: item.mstd,
          },
          iqty:item.syPuQty,
        });
      }
    });
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      console.log(data);
      data.pmPuAppvouchsList = await getPmPuAppvouchsList();
      // console.log('submit', params, data, record);
      const res = await pmPuAppvouchSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
